import json

html_template = """<!DOCTYPE html>
<html style="height: 100%">
    <head>
        <meta charset="utf-8">
    </head>
    <body style="display: flex; height: 100%; margin: 10px;flex-wrap: wrap;justify-content: space-between;">
            {{div}}
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
        <script type="text/javascript">
            {{script}}
        </script>
    </body>
</html>
"""


def trans_data(data):
    # data={'title': '标题', 'keys': [每一列的名称], '属性名1': [属性值], '属性名2': [属性值]}
    title = data.pop('title')
    keys = data.pop('keys')
    labels = list(data.keys())
    out = {
        'title': {'text': title},
        'tooltip': {
            'trigger': 'axis'
        },
        'legend': {'data': labels},
        'grid': {
            'left': '3%',
            'right': '4%',
            'bottom': '3%',
            'containLabel': True,
        },
        'toolbox': {
            'feature': {
                'saveAsImage': {}
            }
        },
        'xAxis': {
            'type': 'category',
            'boundaryGap': False,
            'data': keys,
        },
        'yAxis': {
            'type': 'value'
        },
        'series': []
    }
    for label in labels:
        out['series'].append({'name': label, 'type': 'line', 'data': data[label],
                              'markPoint': {'data': [{'type': 'max', 'name': '最大值'}]}
                              })
    return out


def save_html(path, data_list):
    div = ''
    script = ''
    for i, data in enumerate(data_list):
        div_id = f'chart{i}'
        data_id = f'data{i}'
        if data:
            div += f'\n<div id="{div_id}" style="height: 48%; width: 48%;min-width: 48%;max-width: 48%; margin: 10px"></div>'
            script += f'\nvar {div_id} = echarts.init(document.getElementById("{div_id}"))'
            script += f'\nvar {data_id}'
            script += f'\n{data_id} = {json.dumps(trans_data(data), indent=2, ensure_ascii=False)}'
            script += f'\n{div_id}.setOption({data_id})'

    out = html_template.replace('{{div}}', div).replace('{{script}}', script)
    with open(path, 'w', encoding='utf8') as f:
        f.write(out)


def save_score_html(path, score):
    keys = [str(i) for i in range(len(score['history']))]
    data_list = []
    loss = {
        'title': 'loss',
        'keys': keys,
        'loss': [round(t['loss'], 4) for t in score['history']]
    }
    data_list.append(loss)

    labels = list(score['best']['train'].keys())
    for dtype in ['train', 'valid', 'test']:
        data = {
            'title': dtype,
            'keys': keys,
        }
        for label in labels:
            data[label] = []
            for one in score['history']:
                v = one[dtype][label]
                data[label].append(round(v, 3))
        data_list.append(data)

    save_html(path, data_list)


if __name__ == '__main__':
    score = json.load(open('../data/score.json', encoding='utf8'))
    save_score_html('../data/score.html', score)
